package com.everflourish.yeah100.http;

import android.text.TextUtils;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.JsonObjectRequest;
import com.everflourish.yeah100.adapter.FragmentStudentAdapter;
import com.everflourish.yeah100.entity.Examination;
import com.everflourish.yeah100.entity.clazz.ClassManage;
import com.everflourish.yeah100.entity.marking.ExaminationBase;
import com.everflourish.yeah100.entity.marking.Standard;
import com.everflourish.yeah100.entity.marking.Student;
import com.everflourish.yeah100.entity.marking.Topic;
import com.everflourish.yeah100.utils.constant.PaperType;
import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 阅卷接口封装
 *
 * @author pf
 * @date 2015-1-14
 */
public class MarkingSystemRequest extends BaseRequest {
    private static MarkingSystemRequest mRequest;

    private MarkingSystemRequest() {
    }

    public static MarkingSystemRequest getInstance() {
        if (mRequest == null) {
            mRequest = new MarkingSystemRequest();
        }
        return mRequest;
    }

    /**
     * 创建考试信息请求
     *
     * @param listener
     * @param errorListener
     * @return
     */
    public JsonObjectRequest createBasicInfoRequest(
            Listener<JSONObject> listener, ErrorListener errorListener) {
        JsonObjectRequest request = new JsonObjectRequest(Method.GET,
                URL_E_BASICINFO_CREATE, null, listener,
                errorListener) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                return addRequestHeader();
            }
        };
        request.setRetryPolicy(new DefaultRetryPolicy(DEFAULT_TIMEOUT_MS,
                DEFAULT_MAX_RETRIES, DEFAULT_BACKOFF_MULT));
        return request;
    }

    /**
     * 修改基础信息请求
     *
     * @param examinationBase
     * @param listener
     * @param errorListener
     * @return
     */
    public JsonObjectRequest updateBasicInfoRequest(
            ExaminationBase examinationBase, Listener<JSONObject> listener,
            ErrorListener errorListener) {
        JsonObjectRequest request = null;
        Gson gson = new Gson();
        String jsonStr = gson.toJson(examinationBase);
        JSONObject jsonObject;
        try {
            jsonObject = new JSONObject(jsonStr);
            request = new JsonObjectRequest(Method.POST,
                    URL_E_BASICINFO_UPDATE, jsonObject, listener, errorListener) {
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    return addRequestHeader();
                }
            };
        } catch (JSONException e) {
            e.printStackTrace();
        }
        request.setRetryPolicy(new DefaultRetryPolicy(DEFAULT_TIMEOUT_MS,
                DEFAULT_MAX_RETRIES, DEFAULT_BACKOFF_MULT));
        return request;
    }

    /**
     * 上传基础信息请求
     *
     * @param examinationBase
     * @param listener
     * @param errorListener
     * @return
     */
    public JsonObjectRequest uploadBasicInfoRequest(
            ExaminationBase examinationBase, Listener<JSONObject> listener,
            ErrorListener errorListener) {
        JsonObjectRequest request = null;
        Gson gson = new Gson();
        String jsonStr = gson.toJson(examinationBase);
        JSONObject jsonObject;
        try {
            jsonObject = new JSONObject(jsonStr);
            request = new JsonObjectRequest(Method.POST,
                    URL_E_BASICINFO_UPLOAD, jsonObject, listener, errorListener) {
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    return addRequestHeader();
                }
            };
        } catch (JSONException e) {
            e.printStackTrace();
        }
        request.setRetryPolicy(new DefaultRetryPolicy(DEFAULT_TIMEOUT_MS,
                DEFAULT_MAX_RETRIES, DEFAULT_BACKOFF_MULT));
        return request;
    }

    /**
     * 获取基础信息请求
     *
     * @param examinationId
     * @param listener
     * @param errorListener
     * @return
     */
    public JsonObjectRequest getBasicInfoRequest(String examinationId,
                                                 Listener<JSONObject> listener, ErrorListener errorListener) {
        JsonObjectRequest request = new JsonObjectRequest(Method.GET,
                URL_E_BASICINFO_GET + examinationId, null, listener,
                errorListener) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                return addRequestHeader();
            }
        };
        request.setRetryPolicy(new DefaultRetryPolicy(DEFAULT_TIMEOUT_MS,
                DEFAULT_MAX_RETRIES, DEFAULT_BACKOFF_MULT));
        return request;
    }

    /**
     * 上传题型请求
     *
     * @param examinationId
     * @param lastModifiedTime
     * @param topics
     * @param listener
     * @param errorListener
     * @return
     */
    public JsonObjectRequest uploadTopicsRequest(String examinationId,
                                                 String lastModifiedTime, List<Topic> topics,
                                                 Listener<JSONObject> listener, ErrorListener errorListener) {
        JsonObjectRequest request = null;
        Gson gson = new Gson();
        String topicsJsonStr = gson.toJson(topics);
        JSONObject jsonObject;
        try {
            JSONArray jsonArray = new JSONArray(topicsJsonStr);
            jsonObject = new JSONObject();
            jsonObject.put("examinationId", examinationId);
            jsonObject.put("topics", jsonArray);
            jsonObject.put("lastModifiedTime", lastModifiedTime);
            request = new JsonObjectRequest(Method.POST, URL_E_TOPICS_UPLOAD,
                    jsonObject, listener, errorListener) {
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    return addRequestHeader();
                }
            };
        } catch (JSONException e) {
            e.printStackTrace();
        }
        request.setRetryPolicy(new DefaultRetryPolicy(DEFAULT_TIMEOUT_MS,
                DEFAULT_MAX_RETRIES, DEFAULT_BACKOFF_MULT));
        return request;
    }

    /**
     * 获取题型请求
     *
     * @param examinationId
     * @param listener
     * @param errorListener
     * @return
     */
    public JsonObjectRequest getTopicsRequest(String examinationId,
                                              Listener<JSONObject> listener, ErrorListener errorListener) {
        JsonObjectRequest request = new JsonObjectRequest(Method.GET,
                URL_E_TOPICS_GET + examinationId, null, listener, errorListener) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                return addRequestHeader();
            }
        };
        return request;
    }

    /**
     * 上传标准答案请求
     *
     * @param examinationId
     * @param lastModifiedTime
     * @param standards
     * @param listener
     * @param errorListener
     * @return
     */
    public JsonObjectRequest uploadStandardRequest(String examinationId,
                                                   String lastModifiedTime, List<Standard> standards,
                                                   Listener<JSONObject> listener, ErrorListener errorListener) {
        JsonObjectRequest request = null;
        Gson gson = new Gson();
        String standardsJsonStr = gson.toJson(standards);
        JSONObject jsonObject;
        try {
            JSONArray jsonArray = new JSONArray(standardsJsonStr);
            jsonObject = new JSONObject();
            jsonObject.put("examinationId", examinationId);
            jsonObject.put("standardAnswers", jsonArray);
            jsonObject.put("lastModifiedTime", lastModifiedTime);
            request = new JsonObjectRequest(Method.POST,
                    URL_E_STANDARDANSWERS_UPLOAD, jsonObject, listener,
                    errorListener) {
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    return addRequestHeader();
                }
            };
        } catch (JSONException e) {
            e.printStackTrace();
        }
        request.setRetryPolicy(new DefaultRetryPolicy(DEFAULT_TIMEOUT_MS,
                DEFAULT_MAX_RETRIES, DEFAULT_BACKOFF_MULT));
        return request;
    }

    /**
     * 获取标准答案请求
     *
     * @param examinationId
     * @param listener
     * @param errorListener
     * @return
     */
    public JsonObjectRequest getStudentAnswersRequest(String examinationId,
                                                      Listener<JSONObject> listener, ErrorListener errorListener) {
        JsonObjectRequest request = new JsonObjectRequest(Method.GET,
                URL_E_STUDENTANSWERS_GET + examinationId, null, listener,
                errorListener) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                return addRequestHeader();
            }
        };
        return request;
    }

    /**
     * 阅卷部分数据获取合并（题型、标准答案、考生答案）
     *
     * @param examinationId
     * @param listener
     * @param errorListener
     * @return
     */
    public JsonObjectRequest getAggregateRequest(String examinationId,
                                                 boolean isGetTopics, boolean isGetAnswers,
                                                 boolean isGetStudentAnswers, Listener<JSONObject> listener,
                                                 ErrorListener errorListener) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("examinationId", examinationId);
        if (isGetAnswers) {
            map.put("isGetTopics", "1");
        }
        if (isGetAnswers) {
            map.put("isGetAnswers", "1");
        }
        if (isGetAnswers) {
            map.put("isGetStudentAnswers", "1");
        }
        JSONObject jsonObject = new JSONObject(map);
        JsonObjectRequest request = new JsonObjectRequest(Method.POST,
                URL_E_AGGREGATE_GET, jsonObject, listener, errorListener) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                return addRequestHeader();
            }
        };
        return request;
    }

    /**
     * 上传单个学生答案请求
     *
     * @param examinationId 考试的Id
     * @param classManages  班级列表
     * @param student       上传的学生信息
     * @param listener
     * @param errorListener
     * @return
     */
    public JsonObjectRequest uploadSingleStudentAnswersRequest(
            String examinationId, String lastModifiedTime,
            List<ClassManage> classManages, Student student,
            Listener<JSONObject> listener, ErrorListener errorListener) {
        List<ClassManage> tempClassManages = new ArrayList<ClassManage>();
        boolean flag = false;
        for (ClassManage c : classManages) {
            ClassManage tempC = new ClassManage();
            ArrayList<Student> tempSList = new ArrayList<Student>();
            for (Student s : c.getStudents()) {
                if (s.getId().equals(student.getId())) {
                    if (TextUtils.isEmpty(s.getAnswer().getPaperType())) {
                        s.getAnswer().setPaperType(PaperType.NONE.text);
                    }
                    tempSList.add(student);
                    flag = true;
                    break;
                }
            }
            tempC.setId(c.getId());
            tempC.setStudents(tempSList);
            tempC.setCreateTime(null);
            tempC.setSize(null);
            tempC.setImagePath(null);
            tempClassManages.add(tempC);
            if (flag) {
                break;
            }
        }
        JsonObjectRequest request = null;
        Gson gson = new Gson();
        String studentsJsonStr = gson.toJson(tempClassManages);
        JSONObject jsonObject;
        try {
            JSONArray jsonArray = new JSONArray(studentsJsonStr);
            JSONObject classJsonObj = new JSONObject();
            classJsonObj.put("classes", jsonArray);
            jsonObject = new JSONObject();
            jsonObject.put("examinationId", examinationId);
            jsonObject.put("studentAnswers", classJsonObj);
            jsonObject.put("lastModifiedTime", lastModifiedTime);
            request = new JsonObjectRequest(Method.POST,
                    URL_E_STUDENTANSWERS_UPLOAD, jsonObject, listener,
                    errorListener) {
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    return addRequestHeader();
                }
            };
        } catch (JSONException e) {
            e.printStackTrace();
        }
        request.setRetryPolicy(new DefaultRetryPolicy(DEFAULT_TIMEOUT_9S,
                DEFAULT_MAX_RETRIES, DEFAULT_BACKOFF_MULT));
        return request;
    }

    /**
     * 上传学生答案请求
     *
     * @param examinationId
     * @param classManages
     * @param listener
     * @param errorListener
     * @return
     */
    public JsonObjectRequest uploadStudentAnswersRequest(String examinationId,
                                                         String lastModifiedTime, List<ClassManage> classManages,
                                                         Listener<JSONObject> listener, ErrorListener errorListener) {
        List<ClassManage> tempClassManages = new ArrayList<ClassManage>();
        for (ClassManage c : classManages) {
            ClassManage tempC = new ClassManage();
            ArrayList<Student> students = new ArrayList<Student>();
            for (Student s : c.getStudents()) {
                if (s.getUploadStatus() == null
                        || s.getUploadStatus() != FragmentStudentAdapter.UPLOAD_FAILURE
                        && s.getUploadStatus() != FragmentStudentAdapter.UPLOADING) {
                    continue;
                }
                // 一键上传 正在上传或者上传失败的学生分数
                students.add(s);
            }
            tempC.setId(c.getId());
            tempC.setStudents(students);
            tempC.setCreateTime(null);
            tempC.setSize(null);
            tempC.setImagePath(null);
            tempClassManages.add(tempC);
        }
        JsonObjectRequest request = null;
        Gson gson = new Gson();
        String studentsJsonStr = gson.toJson(tempClassManages);
        JSONObject jsonObject;
        try {
            JSONArray jsonArray = new JSONArray(studentsJsonStr);
            JSONObject classJsonObj = new JSONObject();
            classJsonObj.put("classes", jsonArray);
            jsonObject = new JSONObject();
            jsonObject.put("examinationId", examinationId);
            jsonObject.put("studentAnswers", classJsonObj);
            jsonObject.put("lastModifiedTime", lastModifiedTime);
            request = new JsonObjectRequest(Method.POST,
                    URL_E_STUDENTANSWERS_UPLOAD, jsonObject, listener,
                    errorListener) {
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    return addRequestHeader();
                }
            };
        } catch (JSONException e) {
            e.printStackTrace();
        }
        request.setRetryPolicy(new DefaultRetryPolicy(DEFAULT_TIMEOUT_MS,
                DEFAULT_MAX_RETRIES, DEFAULT_BACKOFF_MULT));
        return request;
    }


    /**
     * 获取标准答案请求
     *
     * @param examinationId
     * @param listener
     * @param errorListener
     * @return
     */
    public JsonObjectRequest getStandardRequest(String examinationId,
                                                Listener<JSONObject> listener, ErrorListener errorListener) {
        JsonObjectRequest request = new JsonObjectRequest(Method.GET,
                URL_E_STANDARDANSWERS_GET + examinationId, null, listener,
                errorListener) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                return addRequestHeader();
            }
        };
        return request;
    }

    /**
     * 上传标准答案切换
     *
     * @param examination
     * @param listener
     * @param errorListener
     * @return
     */
    public JsonObjectRequest uploadStudentSubAnswerSwitchRequest(
            Examination examination, Listener<JSONObject> listener,
            ErrorListener errorListener) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("examinationId", examination.getId());
        if (examination.getSubjectFlag() != null) {
            map.put("subjectFlag",
                    examination.getSubjectFlag().equals("1") ? "2" : "1");
        } else {
            map.put("subjectFlag", "2");
        }
        JSONObject jsonObject = new JSONObject(map);
        JsonObjectRequest request = new JsonObjectRequest(Method.POST,
                URL_E_SUBJECT_SWITCH, jsonObject, listener, errorListener) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                return addRequestHeader();
            }
        };
        return request;
    }

    /**
     * 获取共享老师记录
     *
     * @param listener
     * @param errorListener
     * @return
     */
    public JsonObjectRequest getShareTeacherRecordsRequest(
            Listener<JSONObject> listener, ErrorListener errorListener) {
        JsonObjectRequest request = new JsonObjectRequest(Method.GET,
                URL_E_TEACHER_SHARE_GET, null, listener, errorListener) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                return addRequestHeader();
            }
        };
        return request;
    }

    /**
     * 删除共享老师
     *
     * @param ids
     * @param listener
     * @param errorListener
     * @return
     */
    public JsonObjectRequest deteleShareTeacherRequest(List<String> ids,
                                                       Listener<JSONObject> listener, ErrorListener errorListener) {
        JSONObject jsonObject = null;
        Gson gson = new Gson();
        String idsJsonStr = gson.toJson(ids);
        JsonObjectRequest request = null;
        JSONArray jsonArray = null;
        try {
            jsonArray = new JSONArray(idsJsonStr);
            jsonObject = new JSONObject();
            jsonObject.put("ids", jsonArray);
            request = new JsonObjectRequest(Method.POST,
                    URL_E_TEACHER_SHARE_DELETE, jsonObject, listener,
                    errorListener) {
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    return addRequestHeader();
                }
            };
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return request;
    }

    /***
     * 获取最后一次考试的基础信息
     *
     * @param listener
     * @param errorListener
     * @return
     */
    public JsonObjectRequest getLastBasicInfoExaminationRequest(
            Listener<JSONObject> listener, ErrorListener errorListener) {
        JsonObjectRequest request = new JsonObjectRequest(Method.GET,
                URL_E_TEACHER_GET_LAST_EXAMIANTION, null, listener,
                errorListener) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                return addRequestHeader();
            }
        };
        request.setRetryPolicy(new DefaultRetryPolicy(DEFAULT_TIMEOUT_MS,
                DEFAULT_MAX_RETRIES, DEFAULT_BACKOFF_MULT));
        return request;
    }


    /**
     * 获取数据校对列表
     *
     * @param listener
     * @param errorListener
     * @return
     */
    public JsonObjectRequest getErrorInfoExaminationRequest(String examinationId,
                                                            Listener<JSONObject> listener, ErrorListener errorListener) {
        JsonObjectRequest request = new JsonObjectRequest(Method.GET,
                URL_PROOFEADING_LIST.replace("{examId}", examinationId), null, listener,
                errorListener) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                return addRequestHeader();
            }
        };
        request.setRetryPolicy(new DefaultRetryPolicy(DEFAULT_TIMEOUT_MS,
                DEFAULT_MAX_RETRIES, DEFAULT_BACKOFF_MULT));
        return request;
    }


    /**
     * 校对数据获取学生答案
     *
     * @param examinationId
     * @param studentNo
     * @param listener
     * @param errorListener
     * @return
     */
    public JsonObjectRequest getStudentAnswerRequest(String examinationId, String studentNo,
                                                     Listener<JSONObject> listener, ErrorListener errorListener) {


        JsonObjectRequest request = new JsonObjectRequest(Method.GET,
                (URL_PROOFREAD_STUDENT_CORRECT.replace("{examId}", examinationId)).replace("{studentNo}", studentNo),
                null, listener, errorListener) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                return addRequestHeader();
            }
        };
        request.setRetryPolicy(new DefaultRetryPolicy(DEFAULT_TIMEOUT_MS,
                DEFAULT_MAX_RETRIES, DEFAULT_BACKOFF_MULT));
        return request;
    }


    /**
     * 获取新题型设置
     *
     * @param examinationId
     * @param listener
     * @param errorListener
     * @return
     */
    public JsonObjectRequest getTopicTypeList(String examinationId, Listener<JSONObject> listener, ErrorListener errorListener) {

        JSONObject params = new JSONObject();
        try {
            params.put("examinationId", examinationId);
            params.put("isGetTopics","1");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        JsonObjectRequest request = new JsonObjectRequest(Method.POST,
                URL_NEW_TOPIC_SETTIN, params, listener, errorListener) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                return addRequestHeader();
            }
        };
        request.setRetryPolicy(new DefaultRetryPolicy(DEFAULT_TIMEOUT_MS,
                DEFAULT_MAX_RETRIES, DEFAULT_BACKOFF_MULT));
        return request;
    }

}
